﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Nomad.WebSync.Extensions;

namespace Nomad.WebSync.Windows.Pages {
    /// <summary>
    /// Interaction logic for NewAccount.xaml
    /// </summary>
    public partial class NewAccount : Page {
        public NewAccount() {
            InitializeComponent();
        }

        private void createAccount() {
            if (String.IsNullOrEmpty(usernameTextBox.Text))
                throw new Exception("Username is required!");

            if (String.IsNullOrEmpty(passwordTextBox.Password))
                throw new Exception("Password is required!");

            if (passwordTextBox.Password != passwordConfirmationTextBox.Password)
                throw new Exception("Passwords not match!");

            if (String.IsNullOrEmpty(emailTextBox.Text))
                throw new Exception("E-mail is required!");

            if (emailTextBox.Text.IndexOf('@') >= emailTextBox.Text.LastIndexOf('.'))
                throw new Exception("Invalid e-mail!");

            var encryptUsername = usernameTextBox.Text.Encrypt();
            var encryptPassword = passwordTextBox.Password.Encrypt();
            var encryptEmail = emailTextBox.Text.Encrypt();

            using (var service = Services.Desktop.Connect()) {
                service.CreateAccount(encryptUsername, encryptPassword, encryptEmail);

                var result = service.Login(usernameTextBox.Text, encryptPassword);
                if (string.IsNullOrEmpty(result))
                    throw new Exception("Invalid Login");

                App.WebSyncHeader = new WebSyncService.WebSyncHeader();
                App.WebSyncHeader.Session = result;

                MessageBox.Show("New account created!", "Nomad WebSync", MessageBoxButton.OK, MessageBoxImage.Information);

                NavigationService.Navigate(new Pages.Today());
            }
        }
        private void cancel() {
            NavigationService.GoBack();
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                this.cancel();
            } catch (Exception ex) {
                MessageBox.Show(ex.SoapMessage(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }
        private void confirmButton_Click(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                this.createAccount();
            } catch (Exception ex) {
                MessageBox.Show(ex.SoapMessage(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }
    }
}
